package com.qianfeng.android.baoman;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.http.AndroidHttpClient;
import android.os.Build;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.android.volley.AuthFailureError;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HttpClientStack;
import com.android.volley.toolbox.HttpStack;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


public class VolleyActivity extends ActionBarActivity {
    /**
     * 请求对列用于发送网络请求
     */
    private RequestQueue requestQueue;
    private JsonRequest jsonRequest;

    //创建对列
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text);
        //创建一个默认配置的请求对列，同时开一个线程会自动启动
        //因此，请求对列必须在主线程创建，用于请求回来的更新数据
//        requestQueue = Volley.newRequestQueue(this);//内部存储

        //外部存储
        requestQueue = newRequestQueue(this, null);

    }

    ////、/////////////////可以提价Json，并且获取Json的请求、、、、、、、、、、、、
    public void btnJsonRequest() {
        jsonRequest = new JsonObjectRequest(
                "",
                new JSONObject(),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            response.toString(4);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );
        requestQueue.add(jsonRequest);
    }

    public void btnLoadImageOnClick(View v) {
        // 1 发送请求
        //  Volley 已经定义好很多请求类型。
        // add(Request) 方法用于相对列添加请求，对列自动联网。
        StringRequest request = new StringRequest(
                "http://www.baidu.com",
                new Response.Listener<String>() {//这个借口主要用于接收Volley请求的结构，这个方法运行与主线程
                    @Override
                    public void onResponse(String response) {
                        //TODO 处理相应

                    }
                },
                new Response.ErrorListener() {//如果网络请求出错，会回调这个方法
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );
        requestQueue.add(request);
    }


    public void post() {
        //Post请求第一个参数必须写，不然永远都是get请求；
        StringRequest postRequest = new StringRequest(
                Request.Method.POST,
                "",//请求网址
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        ) {
            //TODO 需要准备Post请求数据

            /**
             * 对列会自动调用这个方法，如果有返回值，那么拼成字符串，作为POST数据提交
             * @return
             * @throws AuthFailureError
             */
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<>();
                map.put("name", "abc");
                map.put("password", "123");
                return map;
            }
        };

        requestQueue.add(postRequest);
    }


    /**
     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
     *
     * @param context A {@link android.content.Context} to use for creating the cache dir.
     * @param stack   An {@link HttpStack} to use for the network, or null for default.
     * @return A started {@link RequestQueue} instance.
     */
    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        File cacheDir = null;//new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            cacheDir = new File(context.getExternalCacheDir(), "volley");
        } else {
            cacheDir = new File(context.getCacheDir(), "volley");
        }

        //TODO 检查是否有存储卡，如果有，直接获取存储卡缓存。
        String userAgent = "volley/0";
        try {
            String packageName = context.getPackageName();
            PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
            userAgent = packageName + "/" + info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
        }

        if (stack == null) {
            if (Build.VERSION.SDK_INT >= 9) {
                stack = new HurlStack();
            } else {
                // Prior to Gingerbread, HttpUrlConnection was unreliable.
                // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
            }
        }

        Network network = new BasicNetwork(stack);

        RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
        queue.start();

        return queue;
    }

}
